// 数字过万的处理
export const formartNum = (val) => {
  let num = 0
  val > 9999 ? (num = Math.round((val / 10000) * 10) / 10 + '万') : (num = val)
  return num
}

// 添加歌曲到播放列表，过滤重复的歌曲
export const concatPlayList = (newList = [], oldList = []) => {
  const arr = [...oldList, ...newList]
  const map = new Map()

  for (const item of arr) {
    if (!map.has(item.id)) {
      map.set(item.id, item)
    }
  }

  return [...map.values()]
}

// 添加歌曲到播放列表，过滤重复的歌曲
export const concatPlayLists = (newList = [], oldList = []) => {
  const arr = [...oldList, ...newList]
  const map = new Map()
  for (const item of arr) {
    if (!map.has(item.id)) map.set(item.id, item)
  }
  return [...map.values()]
}

// 处理歌曲
export const formatSongs = (list, privileges) => {
  const result = []
  list.map((item, index) => {
    if (item.id) {
      // 是否有版权播放
      item.license = !privileges[index].cp
      result.push(formatSongInfo(item))
    }
  })
  return result
}

export const formatSongInfo = (params) => {
  return new Song({
    id: String(params.id),
    name: params.name,
    mvId: params.mv,
    singer: params.ar,
    album: params.al,
    alia: params.alia,
    vip: params.fee === 1,
    license: params.license,
    duration: formatSongTime(params.dt),
    url: `https://music.163.com/song/media/outer/url?id=${params.id}.mp3`,
    publishTime: formatMsgTime(params.publishTime)
  })
}

// 时间毫秒格式化处理 2020-10-30 09:30:00
export const formartDate = (originVal, fmt) => {
  const dt = new Date(originVal)
  const opt = {
    yyyy: dt.getFullYear(),
    MM: (dt.getMonth() + 1 + '').padStart(2, '0'),
    dd: (dt.getDate() + '').padStart(2, '0'),
    HH: (dt.getHours() + '').padStart(2, '0'),
    mm: (dt.getMinutes() + '').padStart(2, '0'),
    ss: (dt.getSeconds() + '').padStart(2, '0')
  }
  for (const k in opt) {
    const ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], opt[k])
    }
  }
  return fmt
}

// 歌曲转毫秒格式化处理 03:30 => (3*60+30) * 1000
export const formatSongSecond = (duration) => {
  let arr = duration.split(':'),
    second = 0;
  for (let i = 0; i < arr.length; i++) {
    second += arr[i] * 60 * (arr.length - 1 - i)
  }
  second += arr[arr.length - 1] * 1;
  return second;
}

// 歌曲毫秒格式化处理 03:30
export const formatSongTime = (duration = 0) => {
  duration = duration >= 0 ? duration / 1000 : 0
  const m = (Math.floor(duration / 60) + '').padStart(2, '0')
  const s = (Math.floor(duration % 60) + '').padStart(2, '0')
  return `${m}:${s}`
}

// 评论时间格式化处理
export const formatMsgTime = (duration) => {
  let result = ''
  const NOW = new Date()
  const PAST = new Date(duration)

  // 判断是当天的时间 显示格式 10：30
  if (NOW.toDateString() === PAST.toDateString()) {
    result = formartDate(duration, 'HH:mm')
    // 时间为当年 显示月日 时间戳
  } else if (PAST.getFullYear() === NOW.getFullYear()) {
    result = formartDate(duration, 'MM月dd日 HH:mm')
  } else {
    result = formartDate(duration, 'yyyy年MM月dd日')
  }
  return result
}

// 处理搜索结果音乐数据
export const formatSearchSongs = songs => {
  return songs.map((song) => {
    return new Song({
      id: String(song.id),
      name: song.name,
      mvId: song.mv,
      singer: song.ar.map((artist) => {
        return {
          id: String(artist.id),
          name: artist.name,
          tns: artist.tns || [],
          alias: artist.alias || [],
        };
      }),
      album: {
        id: String(song.al.id),
        name: song.al.name,
        picUrl: song.al.picUrl,
        tns: song.al.tns || [],
        pic_str: song.al.pic_str,
        pic: String(song.al.pic),
      },
      alia: song.alia || [],
      duration: formatSongTime(song.dt),
      url: `https://music.163.com/song/media/outer/url?id=${song.id}.mp3`,
      vip: song.fee === 1,
      license: song.privilege,
      publishTime: formatMsgTime(song.publishTime),
    })
  })
}

// 防抖
export const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

export default class Song {
  constructor({ id, name, mvId, singer, album, alia, duration, url, vip, license, publishTime }) {
    this.id = id
    this.name = name
    this.mvId = mvId
    this.singer = singer
    this.album = album
    this.alia = alia
    this.duration = duration
    this.url = url
    this.vip = vip
    this.license = license
    this.publishTime = publishTime
  }
}

export const formatDate = (timestamp) => {
  if (timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
  }
}